<template>

  <div>

    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="发送消息"
      width="50%"
      @close="handleClose"
    >

      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-position="left" label-width="100px">

        <el-form-item label="消息模板" prop="tmplId">
          <msg-tmpl-select v-model="dataForm.tmplId"/>
        </el-form-item>

        <el-form-item label="接收用户" prop="userIds">
          <el-button type="primary" size="small" @click="userDialog = true">
            添加用户
          </el-button>

          <el-button type="danger" size="small" @click="clearUser">
            清空用户
          </el-button>
          <div style="max-height: 200px; overflow-y: auto">
            <el-tag
              v-for="(item,index) in selectUsers"
              :key="item.id"
              style="margin-right: 10px"
              size="mini"
              closable
              @close="removeUser(index)">
              {{ item.realName }}
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item v-if="dataForm.tmplId" label="发送方式">
          <div>
            <el-checkbox v-if="tmplData.imOn" v-model="dataForm.useIm">站内信</el-checkbox>
            <el-checkbox v-if="tmplData.smsOn" v-model="dataForm.useSms">手机短信</el-checkbox>
            <el-checkbox v-if="tmplData.emailOn" v-model="dataForm.useEmail">电子邮件</el-checkbox>
          </div>

          <div style="font-size: 12px; color: orange">
            请至少选择一种方式进行发送，如果选定的用户如果没有邮件或手机号，则不会发送
          </div>

        </el-form-item>

        <div v-if="tmplData.props && tmplData.props.length > 0" style="padding-top: 10px">
          <h3>消息参数</h3>
          <el-table
            :data="tmplData.props"
            border
            stripe
            style="width: 100%">

            <el-table-column
              prop="prop"
              label="参数名称"/>

            <el-table-column
              prop="value"
              label="参数值">
              <template v-slot="scope">
                <el-input v-model="scope.row.value" size="small"/>
              </template>
            </el-table-column>

            <el-table-column
              prop="remark"
              label="参数描述"/>
          </el-table>

        </div>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :disabled="!dataForm.tmplId || (!dataForm.useIm && !dataForm.useSms && !dataForm.useEmail)" :loading="loading" type="primary" @click="handleSave">确 定</el-button>
      </div>

    </el-dialog>

    <user-select-dialog
      :dialog-show.sync="userDialog"
      :excludes="dataForm.userIds"
      @select="userSelected"
    />

  </div>

</template>

<script>
import { fetchDetail } from '@/api/notify/tmpl'
import { manualSend } from '@/api/notify/msg'

import UserSelectDialog from '@/views/admin/sys/user/components/UserSelectDialog'

export default {
  name: 'SendMsgDialog',
  components: { UserSelectDialog },
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    },
    tmplId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      rules: {
        tmplId: [
          { required: true, message: '消息模板不能为空！' }
        ],
        userIds: [
          { required: true, message: '接收用户必须选择！' }
        ]
      },
      mobileStr: '',
      emailStr: '',
      dataForm: {
        tmplId: '',
        userIds: []
      },
      selectUsers: [],
      tmplData: {},
      userDialog: false
    }
  },
  watch: {
    // 检测查询变化
    dialogShow: {
      handler() {
        this.dialogVisible = this.dialogShow
      },
      deep: true
    },
    'dataForm.tmplId': {
      handler(val) {
        this.fetchTmpl(val)
      }
    },
    selectUsers: {
      handler(val) {
        const arr = []
        if (val && val.length>0) {
          for (let i = 0; i<val.length; i++) {
            arr.push(val[i].id)
          }
        }

        this.dataForm.userIds = arr
      }
    },
    tmplId: {
      handler(val) {
        if (val) {
          this.dataForm.tmplId = val
        }
      }
    }
  },
  created() {
    this.dialogVisible = this.dialogShow
    if (this.tmplId) {
      this.dataForm.tmplId = this.tmplId
    }
  },
  methods: {

    handleClose() {
      this.$emit('update:dialogShow', false)
    },

    // 获取模板信息
    fetchTmpl(tmplId) {
      fetchDetail(tmplId).then(res => {
        this.tmplData = res.data
      })
    },

    handleSave() {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) {
          return
        }

        // 构建模板参数
        const props = this.tmplData.props
        if (props && props.length > 0) {
          const params = {}
          for (let i = 0; i<props.length; i++) {
            params[props[i].prop] = props[i].value
          }
          this.dataForm.params = params
        }

        console.log(this.dataForm)

        this.loading = true
        manualSend(this.dataForm).then(() => {
          this.$notify({
            title: '成功',
            message: '消息已提交发送！',
            type: 'success',
            duration: 2000
          })

          // 清空表单
          this.dataForm = {}
          this.selectUsers = []

          this.dialogShow = false
        })
        this.loading = false
      })
    },

    // 添加到列表
    userSelected(ids, objs) {
      if (objs && objs.length > 0) {
        for (let i = 0; i<objs.length; i++) {
          this.selectUsers.push(objs[i])
        }
      }
    },
    clearUser() {
      this.selectUsers = []
    },

    removeUser(index) {
      this.selectUsers.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.doc {
  background: #f0f0f0;
  padding: 8px;
  margin-bottom: 20px;
  border-radius: 5px;
  margin-top: -10px;
}
</style>
